export default function useRouterDefender (router, store) {
    router.beforeEach((to, from) => {
        const isinit = store.state.isinit;
        const userinfo = store.state.userinfo;

        if (to.path !== '/login' && to.path !== '/starter' && !isinit) {
            return {
                path: '/starter',
                query: { origin: to.fullPath }
            };
        }
        const islogin = store.state.islogin;
        // const islogin = store.state.is_login;
        if (to.meta.requireAuth && !islogin) {
            // 此路由需要授权，请检查是否已登录
            // 如果没有，则重定向到登录页面
            return {
                path: '/login',
                query: { origin: to.fullPath, openid: store.state.userinfo.openid }
            };
        }

        const roles_route = to.matched.find(record => record.meta.roles);
        const user_roles = store.state.roles;

        if (roles_route && !rolesExam(user_roles, roles_route.meta.roles)) {
            return pushMesApp(userinfo);
        }

        // 控制页面头部返回按钮
        const { title } = to.meta;

        document.title = title || '';
    });
}

function rolesExam (roles, targetroles) {
    if (!targetroles) {
        return true;
    }

    if (!roles) {
        return false;
    }
    return roles.some((child) => {
        return targetroles.includes(child);
    });
}

function pushMesApp (userinfo) {
    const app_path = '/webapp/index.html#/index?openid=' + userinfo.openid + '&phone=' + userinfo.phone + '&username=' + userinfo.username + '&token=' + userinfo.NCCLOUD_TOKEN;
    document.location.assign(app_path);
    return {
        path: app_path
    };
}
